package com.teasale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teasale.entity.Order;
import com.teasale.entity.OrderGoods;
import com.teasale.vo.OrderGoodsOV;
import com.teasale.mapper.OrderGoodsMapper;
import com.teasale.service.OrderService;
import com.teasale.mapper.OrderMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
* @author water003
* @description 针对表【order】的数据库操作Service实现
* @createDate 2023-06-06 23:13:52
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Override
    public List<Order> getallByUserId(Integer userid) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userid);
        List<Order> orders = orderMapper.selectList(wrapper);
        return orders;
    }

    @Override
    public List<OrderGoodsOV> find(Integer userId) {
        List<OrderGoodsOV> orderGoodsOVS = orderMapper.selectAllByUserId(userId);
        System.out.println(orderGoodsOVS);

        return orderGoodsOVS;
    }
    /**
     * 新增订单
     * @return
     */
    @Override
    public String addOrders(Integer userId,String [] goodId,double orderPrice,double ogPrice,int[] ogNum) {

        // 生成随机订单编号 sUserId
        //时间（精确到毫秒）
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        //3位随机数
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        int subStrLength = 5;
        String sUserId = userId.toString();
        int length = sUserId.length();
        String str;
        if(length>=subStrLength){
            str = sUserId.substring(length-subStrLength,length);
        }else {
            str = String.format("%0"+subStrLength+"d",userId);
        }
        String orderOutId = localDate +randomNumeric+str;
        System.out.println("订单号："+orderOutId);
        Order order = new Order();
        // 根据用户id创新新的订单
        order.setUserId(userId);
        // 订单创建时间
        order.setOrderTime(new Date());
        // 订单状态
        order.setOrderStatu(0);
        // 订单支付状态
        order.setOrderPay(0);
        // 订单价格
        order.setOrderPrice(orderPrice);
        // 订单编号
        order.setOrderOutId(orderOutId);
        int insert = orderMapper.insert(order);
        // 实例化订单商品关联
        OrderGoods orderGoodsi = new OrderGoods();
        // 订单商品管理表 订单id、订单价格、订单数量
        orderGoodsi.setOrderId(orderOutId);
        orderGoodsi.setOdPrice(ogPrice);
        if (insert==1){
            QueryWrapper queryWrapper = new QueryWrapper<Order>(order);
            List<Order> list = orderMapper.selectList(queryWrapper);
            List<OrderGoods> orderGoods = new ArrayList<>();
            for(int i = 0;i<goodId.length;i++){
                orderGoodsi.setGoodsId(goodId[i]);
                orderGoodsi.setOgNum(ogNum[i]);
                orderGoods.add(orderGoodsi);

            }
            int i = orderGoodsMapper.insertBatchSomeColumn(orderGoods);
            if(i==1){
                System.out.println(orderGoods);
            }
            return "购买成功，正在跳转至支付页...";
        }
        return  "购买失败，请检查登录状态！";

    }

    /**
     * 根据id删除订单
     * @return
     */
    @Override
    public void delOrder(Integer orderId) {
        orderMapper.deleteById(orderId);
    }

    /**
     * 更新订单状态
     * @return
     */
    @Override
    public void updateOrderPayStatus(Integer orderId, Integer status) {
        orderMapper.update(null, Wrappers.lambdaUpdate(Order.class).set(Order::getOrderPay, status).eq(Order::getOrderId, orderId));
    }


    /**
     * 查询所有订单
     * @return
     */
    public List<OrderGoodsOV> selectAllOrder(String id){
        return orderMapper.selectAllOrder(id);
    }
}




